<template>
  <div id="vditor"  class="vditor-preview"></div>
</template>
<script setup>
import Vditor from "vditor";
import "vditor/dist/index.css";
const contentEditor = ref("");

const props = defineProps({
  content: {
    type: String,
    default: ''
  },
  id: {
    type: String,
    default: 'contentId'
  }
})

const emit = defineEmits(['update:outline'])

const initVditor = () => {
  nextTick( () => {
    // 动态导入时使用默认加载方式
    let tocArray = []
    const element = document.getElementById(props.id)
    if (!element) return

    Vditor.preview(element, props.content, {
      speech: {
        enable: false
      },
      cache: {
        enable: false
      },
      width: '100%',
      hljs: {
        style: 'atom-one-dark',
        lineNumber: true,
        enable: true
      },
      anchor: 1,
      after: () => {
        const tocTags = ['H1', 'H2', 'H3', 'H4']
        const childNodes = element.children

        for (let i = 0; i < childNodes.length; i++) {
          const node = childNodes[i]
          if (tocTags.includes(node.tagName)) {
            const id = node.getAttribute('id')
            tocArray.push({
              id: id,
              text: node.textContent.trim(),
              level: Number.parseInt(node.tagName.substring(1)),
              pos: node.offsetTop
            })
          }
        }
        emit('update:outline', tocArray)
      }
    })
  })
}
onMounted(() => {
  contentEditor.value = new Vditor("vditor", {
    height: 360,
    speech: {
      enable: false
    },
    toolbarConfig: {
      pin: false,
    },
    cache: {
      enable: false,
    },
    after: () => {
      contentEditor.value.renderPreview(props.content)
    },
  });


 // initVditor()

});
</script>
<style scoped>
a {
  color: #42b983;
}

.vditor-preview {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}
</style>

